local Logger = {}

-- 初始化日志对象
function Logger:init(appName, options)
    -- 判断文件是否存在
    local fileExists = function(full, dir)
        local file = io.open(full, "r")
        if file then
            io.close(file)
            return true
        else
            os.execute("mkdir " .. dir)
            return false
        end
    end

    self.appName = appName or "TestApp"
    options = options or {}
    self.fileName = options.fileName or "app.log"
    self.parent = options.parent or "./logs/"
    self.level = string.upper(options.level) or "INFO"

    -- 创建日志文件夹和文件
    local fullPath = self.parent .. self.fileName
    local dirPath = string.match(fullPath, "(.*)/")
    fileExists(fullPath, dirPath)

    --   io.open(fullPath, "a"):close()
end

-- 获取当前时间的格式化字符串
local function getCurrentTime()
    local currentTime = os.date("%H:%M:%S")
    return currentTime
end

-- 写日志到文件
function Logger:logToFile(level, msg)
    local currentTime = getCurrentTime()
    local callerInfo = debug.getinfo(2, "Sl")
    local lineInfo = "[" .. callerInfo.short_src .. ":" .. callerInfo.currentline .. "]"
    local fullPath = self.parent .. self.fileName
    local logMessage = string.format("[%s] - %s - %s - %s - %s", self.appName, currentTime, level, lineInfo, msg)

    -- 添加日志级别过滤逻辑
    if self:shouldLog(level) then
        io.open(fullPath, "a"):write(logMessage .. "\n"):close()
        print(logMessage)
    end
end

-- 检查是否应该记录指定级别的日志
function Logger:shouldLog(logLevel)
    if self.level == "INFO" or self.level == "DEBUG" then
        return true
    elseif logLevel == "ERROR" and self.level == "ERROR" then
        return true
    else
        return false
    end
end

-- 写错误日志到文件
function Logger:error(msg)
    self:logToFile("ERRO", msg)
end

-- 写信息日志到文件
function Logger:info(msg)
    self:logToFile("INFO", msg)
end

-- 写调试日志到文件
function Logger:debug(msg)
    self:logToFile("DEBUG", msg)
end

return Logger
